package class02_异或运算.test;

public class Code02_EvenTimesOddTimes {
    public static void printOddTimesNum1(int[] arr){
        if(arr == null || arr.length < 2){
            return;
        }
        int eor = 0;
        for (int i = 0; i < arr.length; i++) {
            eor ^= arr[i];
        }
        System.out.println(eor);
    }

    public static void main(String[] args) {
        int[] arr = new int[]{4,4,4,4,4,4,3,3,3};
        printOddTimesNum1(arr);


        int[] arr1 = {3,1,100};

        int i = 0;
        int j = 0;

        arr[i] = arr[i] ^ arr[j];
        arr[j] = arr[i] ^ arr[j];
        arr[i] = arr[i] ^ arr[j];

        System.out.println(arr[i] + " , " + arr[j]);
        System.out.println(arr[0]);
        System.out.println(arr[2]);

        swap(arr, 0, 0);

        System.out.println(arr[0]);
        System.out.println(arr[2]);


        int[] arr2 = new int[]{4,4,4,4,4,4,3,3,3,99,99,99,99,99,55,55,55,55,1,1,1,1,1,1};
        printOddTimesNum2(arr2);
    }

    public static void swap (int[] arr, int i, int j) {
        // arr[0] = arr[0] ^ arr[0];
        arr[i]  = arr[i] ^ arr[j];
        arr[j]  = arr[i] ^ arr[j];
        arr[i]  = arr[i] ^ arr[j];
    }


    public static void printOddTimesNum2(int[] arr){
        int eor = 0;
        //a ^ b
        for (int i = 0; i < arr.length; i++) {
            eor ^= arr[i];
        }
        //取最右边的一个，说明a和b在此处一个是0一个是1
        int right = eor & (-eor);
        int oneNumber = 0;
        for (int i = 0; i < arr.length; i++) {
            if((right & arr[i]) == 0){
                oneNumber ^= arr[i];
            }
        }
        System.out.println("oneNumber= " +oneNumber+"otherNumber=" + (eor ^oneNumber));

    }

}
